﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;

namespace webapi.Models
{
  public class DB
  {
    protected static string connString = ConfigurationSettings.AppSettings["ConnectionString"];

    public DB()
    {
    }
    /// <summary>
    /// 执行select类型的sql语句,返回select得到的数据集
    /// </summary>
    /// <param name="sqlSelect">select语句</param>
    /// <returns>返回select得到的数据集</returns>
    public static DataSet ExecuteSelectSql(string sqlSelect)
    {
      SqlConnection conn = new SqlConnection(connString);
      SqlDataAdapter sda = new SqlDataAdapter(sqlSelect, conn);
      DataSet ds = new DataSet();
      try
      {
        sda.Fill(ds);
      }
      catch (SqlException e)
      {
        throw new Exception(e.Message);
      }
      return ds;
    }


    /// <summary>
    /// 执行insert,update,delete等语句,改变的行数
    /// </summary>
    /// <param name="sql">sql语句</param>
    /// <returns>改变的行数</returns>
    public static int ExecuteSql(string sql)
    {
      int rows = -1;
      SqlConnection conn = new SqlConnection(connString);
      SqlCommand cmd = new SqlCommand(sql, conn);
      try
      {
        conn.Open();
        rows = cmd.ExecuteNonQuery();
      }
      catch (SqlException e)
      {
        throw new Exception(e.Message);
      }
      finally
      {
        cmd.Dispose();
        conn.Close();
      }

      return rows;
    }
  }
}